<template>
  <el-dialog title="选择疏东坡商品" :visible.sync="showDialog" :before-close="closeDialog" :close-on-click-modal="false"
    width="1200px" top="100px">
    <el-row type="flex" justify="space-around">
      <el-col :span="24">
        <el-form class="search clearfix" :inline="true" label-suffix="：" size="mini" :model="search">
          <!-- 商品筛选条件 -->
          <el-row>
            <el-form-item>
              <el-input v-model="search.searchValue" class="w300" clearable placeholder="搜索商品名称,商品编码,助记码"
                @keyup.enter.native="getList('search')">
                <el-button slot="append" icon="el-icon-search" @click="getList('search')" />
              </el-input>
            </el-form-item>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="space-around" class="border-bottom pb20">
      <el-col :span="4">
        <div class="tree-header">供应链商品分类</div>
        <el-tree :data="options.category" :props="{children: 'items', label: 'name'}" check-on-click-node
          highlight-current accordion class="tree-content" @node-click="changeTreeNode" />
      </el-col>
      <el-col :span="20">
        <el-table ref="productList" size="small" height="500" :data="list" :cell-style="$style.cellStyle"
          :header-cell-style="$style.rowClass" @selection-change="handleSelectionChange">
          <el-table-column type="selection" :selectable="handleSelectable" width="55" />
          <el-table-column label="商品编码" prop="commodityCode" width="200" />
          <el-table-column label="商品名称" prop="name" />
          <el-table-column label="商品pid" prop="id" />
          <el-table-column label="基础单位" prop="unit" />
          <el-table-column label="状态">
            <template slot-scope="{row}">
              <el-tag v-if="row.status === 'Y'" type="success">正常</el-tag>
              <el-tag v-else-if="row.status === 'N'" type="warning">删除</el-tag>
              <el-tag v-else type="danger">彻底删除</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination class="page tc mt10" :total="page.total" :page.sync="page.current" :limit.sync="page.size"
          @pagination="getList" />
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="getSelect()">确 定</el-button>
      <el-button size="small" @click="closeDialog()">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
class Search {
  constructor() {
    this.categoryId1 = ''; // 一级分类id
    this.categoryId2 = ''; // 二级分类id
    this.searchValue = ''; // 商品id精确查询
  }
}
class Page {
  constructor() {
    this.total = 0;
    this.current = 1;
    this.size = 10;
  }
}
class Options {
  constructor() {
    this.category = [];
    this.productStatus = [
      { id: 0, name: '正常', type: 'success' },
      { id: 1, name: '停售', type: 'danger' },
      { id: 2, name: '淘汰', type: 'warning' },
      { id: 3, name: '删除', type: 'info' }
    ]; // 商品状态
    this.storeStatus = [
      { id: 1, name: '正常', type: 'success' },
      { id: 2, name: '停用', type: 'danger' }
    ]; // 门店状态
    this.storeType = [
      { id: 1, name: '直营店', type: 'danger' },
      { id: 2, name: '加盟店', type: 'warning' }
    ]; // 门店类型
  }
}
import {
  selectSdpCommodityCategoryList,
  selectSdpQueryProductList
} from '@/api/goods';
import pagination from '@/components/Pagination';
export default {
  name: 'Search',
  components: {
    pagination
  },
  props: {
    searchParams: {
      type: Object,
      default: () => {
        return {};
      }
    }, // 搜索附加参数 ,对象形式，默认为空
    selectMode: {
      type: String,
      default: 'single'
    }, // 选择模式，single 单选；multiple 多选
    showDialog: {
      type: Boolean,
      default: false
    }, // 开关
    defaultDatas: {
      type: Array,
      default: () => []
    }, // 默认回显数据
    showSelected: {
      type: Boolean,
      default: false
    } // 回显标识
  },
  data () {
    return {
      page: new Page(), // 列表分页
      search: new Search(), // 列表搜索
      options: new Options(), // 搜索项
      list: [], // 商品列表
      selectedDatas: []
    };
  },
  watch: {
    showDialog (newVal) {
      if (newVal) {
        this.getOptions();
        this.open();
      }
    }
  },
  methods: {
    open () {
      this.selectedDatas = [];
      if (this.defaultDatas.length > 0) {
        this.selectedDatas = JSON.parse(JSON.stringify(this.defaultDatas));
      }
      this.checkedProduct();
    },
    // 用于已选商品进行回显
    checkedProduct () {
      if (this.showSelected) { // 匹配pruductId
        const ids = this.selectedDatas.map(val => val.productId);
        this.list.forEach(item => {
          if (ids.includes(item.productId)) {
            this.$nextTick(() => {
              this.$refs['productList'].toggleRowSelection(item, true);
            });
          }
        });
      }
    },
    // 获取条件选项
    async getOptions () {
      const data = await selectSdpCommodityCategoryList();
      this.options.category = [{ name: '全部分类', id: '' }, ...data];
      this.getList('search');
    },
    // 获取商品列表
    async getList (type) {
      if (type === 'search') this.page = new Page();
      try {
        const { records, total } = await selectSdpQueryProductList({
          ...this.page,
          ...this.search,
          ...this.searchParams
        });
        this.page.total = total * 1;
        this.list = records;
        this.checkedProduct();
      } catch (e) {
        this.page.total = 0;
        this.list = [];
      }
    },
    // 切换左侧分类
    changeTreeNode (val) {
      if (val.items && val.items.length > 0) { // 点击节点存在子项
        this.search.categoryId1 = val.id; // 赋值一级分类
        this.search.categoryId2 = '';
      } else { // 不存在子项
        this.search.categoryId1 = '';
        this.search.categoryId2 = val.id; // 赋值二级分类
      }
      this.getList('search');
    },
    // 是否可选
    handleSelectable (row) {
      return row.isCheckCode < 1; // 已对码的商品不可选
    },

    // 关闭弹窗
    closeDialog () {
      this.search = new Search();
      this.$refs['productList'].clearSelection();
      this.$emit('closeDialog');
    },
    // 当用户手动勾选数据行的 Checkbox 时触发的事件
    handleSelectionChange (selection) {
      this.selectedDatas = selection;
    },
    // 确定选项
    getSelect () {
      if (this.selectMode === 'single' && this.selectedDatas.length > 1) return this.$notification('选择过多', 'warning', '目前只支持选取单项。');
      // 数组去重
      Array.from(new Set(this.selectedDatas));
      let arr = {};
      arr.option = this.selectedDatas; // 选项赋值，用于筛选框回显
      arr.selected = this.selectedDatas.map(val => val.commodityCode); // 筛选项赋值，用于筛选框回显
      this.$emit('getSelect', arr);
      this.closeDialog();
    }
  }
};
</script>

<style scoped lang="scss">
.tree-header {
  height: 40px;
  background: #f9fafc;
  color: #909399;
  font-size: 12px;
  font-weight: bold;
  line-height: 40px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
}
.tree-content {
  height: 460px;
  overflow-y: scroll;
}
.border-bottom {
  border-bottom: 1px solid #ebeef5;
}
</style>
